package com.chinatcc.proxy.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImgCodeUtil {

	private static final int HEIGHT = 30;
	private static final int NUM = 4;
	private static final char[] seq = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
			'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
			'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9' };

	private static final int WIDTH = 120;

	private String code;

	public byte[] generateImg() {
		Random r = new Random();

		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);

		Graphics g = image.getGraphics();
		g.setColor(this.getRandColor(211, 212));
		g.fillRect(0, 0, WIDTH, HEIGHT);
		g.setColor(this.getRandColor(199, 211));

		StringBuffer number = new StringBuffer();

		for (int i = 0; i < NUM; i++) {
			g.setColor(this.getRandColor(55, 122));
			int h = (int) ((HEIGHT * 60 / 100) * r.nextDouble() + (HEIGHT * 50 / 100));
			g.setFont(new Font(null, Font.BOLD | Font.ITALIC, h));
			String ch = String.valueOf(seq[r.nextInt(seq.length)]);
			number.append(ch);
			g.drawString(ch, i * WIDTH / NUM * 90 / 100, h);
		}

		for (int i = 0; i <= 2; i++) {
			g.setColor(this.getRandColor(111, 222));
			g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT), r.nextInt(WIDTH), r
					.nextInt(HEIGHT));

		}

		ByteArrayOutputStream os = new ByteArrayOutputStream();

		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);

		try {
			encoder.encode(image);
			return os.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			this.setCode(number.toString());
		}
	}

	public String getCode() {
		return code;
	}

	private Color getRandColor(int fc, int bc) {
		Random rand = new Random();
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}
		int r = fc + rand.nextInt(bc - fc);
		int g = fc + rand.nextInt(bc - fc);
		int b = fc + rand.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	private Color randomColor(Random r) {
		return new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
	}

	private void setCode(String code) {
		this.code = code;
	}
}
